package com.example.BOOK.data;

import android.content.Context;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;

public class Databank {
    public static final String DATA_FILE_NAME = "data";
    private final Context context;
    List<Book>bookList;

    public Databank(Context context) {
        this.context=context;
    }

    public List<Book> loadData() {
        bookList=new ArrayList<>();
        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(context.openFileInput(DATA_FILE_NAME));
            bookList= (ArrayList<Book>) objectInputStream.readObject();
        }catch(Exception e)
        {
            e.printStackTrace();
        }
        return bookList;
    }

    @SuppressWarnings("unchecked")
    public void savedata()
    {
        ObjectOutputStream objectOutputStream=null;
        try{
            ObjectOutputStream outputStream = new ObjectOutputStream(context.openFileOutput(DATA_FILE_NAME, Context.MODE_PRIVATE));
            outputStream.writeObject(bookList);
        }catch(IOException e){
            e.printStackTrace();
        }finally {
            try{
                if(objectOutputStream!=null)
                    objectOutputStream.close();
        }catch(IOException e){
            e.printStackTrace();
            }
        }

    }
}
